<template>
  <div>
    <el-card v-role-button="`btn.User.search`">
      <el-form inline class="form" >
        <el-form-item label="用户名:">
          <el-input placeholder="请输入用户名" v-model="nameKeywork"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!nameKeywork" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="card">
      <el-button type="primary" @click="openDrawer('添加用户')" v-role-button="`btn.User.add`">添加用户</el-button>
      <el-button type="danger" :disabled="!selectionIdArr.length" @click="delectSelectUser" v-role-button="`btn.User.remove`">批量删除</el-button>
      <el-table @selectionChange="selectionChange" v-loading="loading" border :data="dataList">
        <el-table-column prop="id" type="selection" align="center"></el-table-column>
        <el-table-column prop="id" label="id" align="center"></el-table-column>
        <el-table-column prop="name" label="用户名字" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" label="用户名称" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="roleName" label="用户角色" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center"></el-table-column>
        <el-table-column label="操作" width="350" align="center">
          <template v-slot="{row}">
            <el-button type="warning" icon="User" @click="openRoleDrawer(row)" v-role-button="`btn.User.assgin`">分类角色</el-button>
            <el-button type="primary" icon="Edit" @click="openDrawer('修改用户', row)" v-role-button="`btn.User.update`">编辑</el-button>
            <el-popconfirm :title="`你确定要删除用户${row.username}吗？`" width="260" @confirm="deleteUser(row.id)" v-role-button="`btn.User.remove`">
              <template #reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          background
          :page-sizes="[20, 50, 100, 200, 300, 400]"
          layout="prev, pager, next, jumper, ->, total, sizes"
          :total="total"
          @currentChange="currentChange"
          @sizeChange="sizeChange"
      ></el-pagination>
    </el-card>
    <el-drawer v-model="drawer" @closed="closeDrawer">
      <template v-slot:header>
        <h4>{{ drawerTitle }}</h4>
      </template>
      <template v-slot:default>
        <el-form :model="userForm" :rules="userFormRules" ref="userFormRef">
          <el-form-item label="用户名称" prop="username">
            <el-input placeholder="请输入用户名" v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input placeholder="请输入用户昵称" v-model="userForm.name"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userForm.id">
            <el-input type="password" show-password placeholder="请输入用户密码" v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <div style="flex: auto;text-align: right">
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="save">确认</el-button>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </el-drawer>
    <el-drawer v-model="roleDrawer" @closed="closeRoleDrawer">
      <template v-slot:header>
        <h4>分配角色</h4>
      </template>
      <template v-slot:default>
        <el-form>
          <el-form-item label="用户昵称">
            <el-input v-model="roleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAllChange">全选
            </el-checkbox>
            <el-checkbox-group v-model="userRole" @change="handleCheckedRuleChange">
              <el-checkbox v-for="(item, index) in allRole" :key="index" :label="item" :value="item">{{
                  item.roleName
                }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <div style="flex: auto;text-align: right">
              <hr>
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="saveRole">确认</el-button>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
// 当前页码
import {onMounted, reactive, ref, useTemplateRef} from "vue";
import {reqUserAddOrUpdate, reqUserList} from "@/api/acl/user";
import type {Records, UserInter, UserResponseInter} from "@/api/acl/user/type.ts";
import {type CheckboxValueType, ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import {reqAllRole, reqRemoveUser, reqRemoveUserBatch, reqSetUserRole} from "@/api/user";
import type {allRoleResponseInter, roleInter, setRoleInter} from "@/api/user/type.ts";
import type {ResponseInter} from "@/api/commonInterFace.ts";

let currentPage = ref<number>(1);
// 每页条数
let pageSize = ref<number>(20);
let total = ref<number>(0)
let dataList = ref<Records>([])
let loading = ref<boolean>(false)
let nameKeywork = ref<string>('')

onMounted(() => {
  getDataList()
})

// 获取数据函数
const getDataList = async () => {
  loading.value = true
  let res: UserResponseInter = await reqUserList(currentPage.value, pageSize.value, nameKeywork.value)
  if (res.code === 200) {
    total.value = res.data.total
    dataList.value = res.data.records
  } else {
    ElMessage.error(res.message)
  }
  loading.value = false
}
// 搜索
const search = () => {
  getDataList()
}
// 重置搜索
const resetSearch = () => {
  nameKeywork.value = ''
  getDataList()
}
// 当前页改变
const currentChange = (newPage: number) => {
  currentPage.value = newPage
  getDataList()
}
// 每页条数改变
const sizeChange = (newSize: number) => {
  pageSize.value = newSize
  getDataList()
}

// 抽屉
let drawer = ref<boolean>(false)
let drawerTitle = ref<string>('添加用户')
let userForm = reactive<UserInter>({
  id: 0,
  name: '',
  username: '',
  password: ''
})
let formRef = useTemplateRef<FormInstance>('userFormRef')

// 校验规则
let userFormRules = {
  name: [
    {required: true, min: 5, message: '请输入用户昵称且大于5位', trigger: 'blur'}
  ],
  username: [
    {required: true, min: 5, message: '请输入用户名称且大于5位', trigger: 'blur'}
  ],
  password: [
    {required: true, min: 6, message: '请输入用户密码且密码大于6位', trigger: 'blur'}
  ]
}

const openDrawer = (title: string, row?: UserInter) => {
  drawerTitle.value = title
  drawer.value = true
  if (row) {
    userForm.id = row.id
    userForm.name = row.name
    userForm.username = row.username
  }
}

const save = async () => {
  await formRef.value?.validate(async valid => {
    if (!valid) return
    let res = await reqUserAddOrUpdate(userForm)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      drawer.value = false
      if (userForm.id) {
        window.location.reload()
      } {
        await getDataList()
      }
    } else {
      ElMessage.error(res.message)
    }
  })
}
const cancel = () => {
  drawer.value = false
}
const closeDrawer = () => {
  userForm.id = 0
  userForm.name = ''
  userForm.username = ''
  userForm.password = ''
  formRef.value?.clearValidate()
}

// 分配角色抽屉
let roleDrawer = ref<boolean>(false)
let roleForm = reactive<UserInter>({})
let checkAll = ref<boolean>(false)
let indeterminate = ref<boolean>(false)
let userRole = ref<roleInter[]>([])
let allRole = ref<roleInter[]>([])

const openRoleDrawer = async (row: UserInter) => {
  Object.assign(roleForm, row)
  let res: allRoleResponseInter = await reqAllRole(roleForm.id as number)
  if (res.code === 200) {
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    indeterminate.value = allRole.value.length !== userRole.value.length && userRole.value.length > 0
  } else {
    ElMessage.error(res.message)
  }
  roleDrawer.value = true
}

const handleCheckAllChange = (val: CheckboxValueType) => {
  userRole.value = val ? allRole.value : []
  indeterminate.value = false
}

const handleCheckedRuleChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  indeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}

const closeRoleDrawer = () => {
  Object.assign(roleForm, {})
  userRole.value = []
  allRole.value = []
}

// 分配角色
const saveRole = async () => {
  let data: setRoleInter = {
    userId: roleForm.id as number,
    roleIdList: userRole.value.map(item => item.id as number)
  }
  let res: ResponseInter = await reqSetUserRole(data)
  if (res.code === 200) {
    ElMessage.success('操作成功')
    roleDrawer.value = false
    await getDataList()
  } else {
    ElMessage.error(res.message)
  }
}

// 删除某一个用户
const deleteUser = async (id: number) => {
  let res: ResponseInter = await reqRemoveUser(id)
  if (res.code === 200) {
    ElMessage.success('操作成功')
    await getDataList()
  } else {
    ElMessage.error(res.message)
  }
}
// 勾选用户
let selectionIdArr = ref<UserInter[]>([])
const selectionChange = (val: UserInter[]) => {
  selectionIdArr.value = val
}
// 批量删除用户
const delectSelectUser = async () => {
  let idList: number[] = selectionIdArr.value.map(item => item.id as number)
  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    let res: ResponseInter = await reqRemoveUserBatch(idList)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      await getDataList()
    } else {
      ElMessage.error(res.message)
    }
  }catch (e) {}
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-form-item {
    margin-bottom: 0;
  }
}

.card {
  margin: 10px 0;

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
  }
}
</style>
